from textual.app import App, ComposeResult
from textual.widgets import DataTable, Header, Footer
from textual import on, events
from .detector import detect_distro  # 确保检测模块存在
from .plugin_loader import load_plugins  # 确保插件加载模块存在
import os

class MirrorSwitcher(App):
    """基于 Textual 的终端用户界面"""
    
    BINDINGS = [
        ("q", "quit", "退出"),
        ("s", "switch_mirror", "切换镜像")
    ]
    
    def __init__(self, mirrors):
        super().__init__()
        self.sorted_mirrors = sorted(mirrors, key=lambda x: x[1])
        self.distro, _ = detect_distro()
        self.plugins = load_plugins()
        
    def compose(self) -> ComposeResult:
        yield Header()
        yield DataTable()
        yield Footer()
        
    def on_mount(self) -> None:
        table = self.query_one(DataTable)
        table.add_columns("镜像源", "延迟(ms)", "状态")
        for url, latency in self.sorted_mirrors:
            status = "✅" if latency < 100 else "⚠️"
            table.add_row(url, str(latency), status)
            
    def action_switch_mirror(self) -> None:
        """切换选中镜像源"""
        table = self.query_one(DataTable)
        if table.cursor_row is None:
            return
            
        selected_url = self.sorted_mirrors[table.cursor_row][0]
        for plugin_cls in self.plugins:
            if plugin_cls.is_compatible(self.distro):
                try:
                    plugin_cls().apply_mirror(selected_url)
                    self.notify(f"成功切换至 {selected_url}", title="操作成功")
                    return
                except Exception as e:
                    self.log_error(f"切换失败: {str(e)}")
                    return
        self.notify("当前发行版暂无支持插件", title="错误")
        
    def log_error(self, message: str) -> None:
        """记录错误日志"""
        log_path = "/var/log/mirror-tool.log"
        try:
            with open(log_path, "a") as f:
                f.write(f"{message}\n")
            self.notify(f"错误已记录至 {log_path}", title="错误")
        except PermissionError:
            self.notify("无权限写入日志文件", title="权限错误")

def run_tui(mirrors):
    """启动 TUI 界面入口"""
    app = MirrorSwitcher(mirrors)
    app.run()

if __name__ == "__main__":
    # 示例数据，实际应从 speed_test 模块获取
    sample_mirrors = [
        ("https://mirror.tuna.tsinghua.edu.cn", 32),
        ("https://mirrors.aliyun.com", 45)
    ]
    run_tui(sample_mirrors)